package cn.usian.controller;

import cn.usian.common.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {

    @RequestMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
//        输入流，通过输入流读取文件内容
        FileInputStream fileInputStream = new FileInputStream(name);

//        输出流，通过输出流将文件写回到浏览器
//        要向浏览器写回数据，所以通过response响应对象进行写回
        ServletOutputStream outputStream = response.getOutputStream();
//       设置响应类型

        response.setContentType("image/jpeg");
        int len=0;
        byte[] bytes = new byte[1024];
        while((len=fileInputStream.read(bytes))!=-1)
        {
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
//      关闭资源
        outputStream.close();
        fileInputStream.close();
    }

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        String filename = file.getOriginalFilename();
        try {
            file.transferTo(new File("D:/image/"+filename));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String image = "D:/image/"+filename;
        return R.success(image);

    }
}
